# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.


import bs4
import re
import urllib.request
import urllib.error
import xlwt
import sqlite3


def main():
    print("main...")
    baseurl = 'https://www.meiju11.com/search.php?page='

    # 1. crawler website
    # html = askURL(baseurl)
    # print(html)
    datalist = getData(baseurl)
    # 2. parse data

    # 3. save data
    savepath = 'MeiJu.xls'
    saveData(datalist, savepath)

    # 4. save database
    dbpath = 'MeiJu.db'
    saveData2DB(datalist, dbpath)


#############################################
#############################################
findname = re.compile(r'<h5 class="text-overflow" title="(.*?)">')
# findlink = re.compile(r'<a href="(.*?)">')
findauthor = re.compile(r'<div class="subtitle text-muted text-overflow hidden-xs">(.*?)</div>')
# findpicurl = re.compile(r'<a class="videopic lazy" data-original="(.*?)"')
findpicurl = re.compile(r'<a class="videopic lazy" data-original="(.*?)"')
findscore = re.compile(r'<span class="score">(.*?)</span>')
#############################################
#############################################


# 1. crawler website
def getData(baseurl):
    print("getData...")
    datalist = []
    for i in range(0, 6):
        url = baseurl + str(i+1) + '&searchtype=5&tid=2'
        # print(url)
        html = askURL(url)
        # print(html)

        # 1.2 parse data
        # parse html
        soup = bs4.BeautifulSoup(html, "html.parser")
        for item in soup.find_all('li', class_="col-md-2 col-sm-3 col-xs-4"):
            data = []
            item = str(item)
            # print(item)

            # get picurl
            picurl = re.findall(findpicurl, item)
            picurl = ''.join(picurl)

            # print(type(picurl))

            data.append(picurl)
            # print(data)

            # get name
            name = re.findall(findname, item)[0]
            # print(name)

            data.append(name)
            # print(data)
            # print(data)

            # get author
            author = re.findall(findauthor, item)
            author = ''.join(author)
            # print(author)

            data.append(author)

            # get score
            score = re.findall(findscore, item)
            score = ''.join(score)
            # score = int(score)
            # print(score)

            data.append(score)
            # data = [x for x in data if x != []]
            # print(data)
            datalist.append(data)
    # print(datalist)
    return datalist


# 1.2 crawler a url
def askURL(url):
    head = {
        'User-Agent':
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36'
    }
    request = urllib.request.Request(url, headers=head)

    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode("utf-8")
        # print(html)
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    # print(html)
    return html


# 3. save data in xls
def saveData(datalist, savepath):
    print("save...")

    # 创建 workbook 对象
    book = xlwt.Workbook(encoding="utf-8")

    # 创建工作表
    sheet = book.add_sheet('MeiJu', cell_overwrite_ok=True)

    # 列的定义
    col = ("PicUrl", "name", "author", "scores")
    # 写入数据，第一个参数表示行，第二个参数表示列， 第三个参数表示添加的内容
    for i in range(0, 4):
        sheet.write(0, i, col[i])  # 写入列名
    for i in range(0, 216):
        print("第%d条" % (i + 1))
        data = datalist[i]
        for j in range(0, 4):
            sheet.write(i + 1, j, data[j])  # 数据写入

    # 保存数据表
    book.save(savepath)


# save data in DB
def saveData2DB(datalist, dbpath):
    print("DB...")
    init_db(dbpath)
    conn = sqlite3.connect(dbpath)
    cur = conn.cursor()

    for data in datalist:
        for index in range(len(data)):
            # if index == 4 or index == 5:
            #     continue
            data[index] = '"' + data[index] + '"'
        sql = '''
            insert into Meiju (
                pic_link, name, author, score
            )
            values(%s)
            ''' % ",".join(data)
        # test
        # print(sql)

        cur.execute(sql)
        conn.commit()
    cur.close()
    conn.close()


def init_db(dbpath):
    sql = '''
        create table MeiJu
        (
            id integer primary key autoincrement,
            pic_link text,
            name varchar,
            author varchar,
            score numeric
        )
    '''     # 创建数据表
    conn = sqlite3.connect(dbpath)
    curror = conn.cursor()
    curror.execute(sql)
    conn.commit()
    conn.close()


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    main()
    print("EVERYTING IS DONE!!!!")

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
